//
//  ServiceAddressModel.swift
//  
//
//  Created by 孙长坦 on 2022/4/18.
//

import Foundation

public class ServiceAddressModel: Codable, Hashable {
    enum CodingKeys: String, CodingKey {
       
        case apiBaseUrls
        
        case apiBaseUrlIndex
        
        case h5BaseUrls
        
        case h5BaseUrlIndex
        
        case webSocketUrls
        
        case webSocketUrlIndex
    }
    
    var apiBaseUrls: [String]
    
    var apiBaseUrlIndex: Int
    
    var apiBaseUrl: String? {
        guard apiBaseUrlIndex >= 0 && apiBaseUrlIndex < apiBaseUrls.count else {
            return nil
        }
        
        return apiBaseUrls[apiBaseUrlIndex]
    }
        
    var h5BaseUrls: [String]
    
    var h5BaseUrlIndex: Int
    
    var h5BaseUrl: String? {
        guard h5BaseUrlIndex >= 0 && h5BaseUrlIndex < h5BaseUrls.count else {
            return nil
        }
        
        return h5BaseUrls[h5BaseUrlIndex]
    }
    
    var webSocketUrls: [String]

    var webSocketUrlIndex: Int
    
    var webSocketUrl: String? {
        guard webSocketUrlIndex >= 0 && webSocketUrlIndex < webSocketUrls.count else {
            return nil
        }
        
        return webSocketUrls[webSocketUrlIndex]
    }
    
    public lazy var md5: String = {
        let value = "\(apiBaseUrls.joined(separator: ","))_\(apiBaseUrlIndex)_\(h5BaseUrls.joined(separator: ","))_\(h5BaseUrlIndex)_\(webSocketUrls.joined(separator: ","))_\(webSocketUrlIndex)"
        return value.ex.md5
    }()
    
    public static func == (lhs: ServiceAddressModel, rhs: ServiceAddressModel) -> Bool {
        return true
    }
    
    public init(apiBaseUrls: [String], apiBaseUrlIndex: Int = 0,
         h5BaseUrls: [String], h5BaseUrlIndex: Int = 0,
         webSocketUrls: [String], webSocketUrlIndex: Int = 0) {
        
        self.apiBaseUrls = apiBaseUrls
        self.apiBaseUrlIndex = apiBaseUrlIndex
        
        self.h5BaseUrls = h5BaseUrls
        self.h5BaseUrlIndex = h5BaseUrlIndex
        
        self.webSocketUrls = webSocketUrls
        self.webSocketUrlIndex = webSocketUrlIndex
    }
    
    public func hash(into hasher: inout Hasher) {
        hasher.combine(apiBaseUrls)
        hasher.combine(apiBaseUrlIndex)
        
        hasher.combine(apiBaseUrls)
        hasher.combine(h5BaseUrlIndex)
        
        hasher.combine(apiBaseUrls)
        hasher.combine(webSocketUrlIndex)
    }
}
